package dao

import (
	"echo-utils/global"
	"echo-utils/internal/model"
	"math"

	"xorm.io/xorm"
)

type ArticleDao struct {
	engine *xorm.Engine
}

func (s *ArticleDao) AddArticle(article *model.Article) {
	ltp := s.find(article.Localpath)
	if len(ltp) > 0 {
		s.delete(article.Localpath)
	}
	s.insert(article)
}

func (s *ArticleDao) FindAll() []model.Article {
	list := make([]model.Article, 0)
	s.engine.Find(&list)
	return list
}

func (s *ArticleDao) FindAllWithPage(page int, keywords string) map[string]interface{} {
	if page < 1 {
		page = 1
	}
	skip := (page - 1) * 20
	list := make([]model.Article, 0)
	count := 0
	if len(keywords) > 0 {
		kw := "%" + keywords + "%"
		s.engine.Where("title like ? or Keywords like ?", kw, kw).Limit(20, skip).Find(&list)
		total, _ := s.engine.Where("title like ? or Keywords like ?", kw, kw).Count(new(model.Article))
		count = int(total)
	} else {
		s.engine.Limit(20, skip).Find(&list)
		total, _ := s.engine.Count(new(model.Article))
		count = int(total)
	}
	totalPage := math.Ceil(float64(count) / 20)
	result := make(map[string]interface{})
	result["pages"] = int8(totalPage)
	result["count"] = int8(count)
	result["list"] = list
	return result
}

func (s *ArticleDao) FindAllNopage(keywords string) map[string]interface{} {
	list := make([]model.Article, 0)
	count := 0
	if len(keywords) > 0 {
		kw := "%" + keywords + "%"
		s.engine.Where("title like ? or Keywords like ?", kw, kw).Find(&list)
		total, _ := s.engine.Where("title like ? or Keywords like ?", kw, kw).Count(new(model.Article))
		count = int(total)
	} else {
		s.engine.Find(&list)
		total, _ := s.engine.Count(new(model.Article))
		count = int(total)
	}
	totalPage := math.Ceil(float64(count) / 20)
	result := make(map[string]interface{})
	result["pages"] = int8(totalPage)
	result["count"] = int8(count)
	result["list"] = list
	return result
}

func (s *ArticleDao) find(path string) []model.Article {
	list := make([]model.Article, 0)
	s.engine.Where("localpath=?", path).Find(&list)
	return list
}

func (s *ArticleDao) insert(article *model.Article) {
	s.engine.Insert(article)
}

func (s *ArticleDao) delete(path string) {
	sets := new(model.Article)
	s.engine.Where("localpath=?", path).Delete(sets)
}

func NewArticleDao() *ArticleDao {
	return &ArticleDao{
		engine: global.DBEngine,
	}
}
